package nsq_mall

import (
	sqlc "bp/db/sqlc"
	offApportionment "bp/internal/service/entity/off_apportionment"
	offTransaction "bp/internal/service/entity/off_transaction"
	"bp/internal/util"
	"context"
	"fmt"
)

func GetOrderCancelTopic() string {
	return fmt.Sprintf("%s-order_cancel", appID)
}

type OrderCancelNotification struct {
	OutTransNo string `json:"biz_no"`
	OutOrderNo string `json:"order_number"`
	Ts         int64  `json:"timestamp"`
}

// HandleOrderCancel 处理商城系统的订单取消消息(按交易号+订单号-付款后)
func (s *NsqMallComServiceImp) HandleOrderCancel(ctx context.Context, q *sqlc.Queries, ptr *OrderCancelNotification) (err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	outTransNo := ptr.OutTransNo
	outOrderNo := ptr.OutOrderNo
	err = s.entityHub.OffTransactionService.DisableOffTransactionsByOutTransNoAndOutOrderNo(ctx, q,
		&offTransaction.DisableOffTransactionByOutTransNoAndOutOrderNoParam{
			OutTransNo: outTransNo,
			OutOrderNo: outOrderNo,
		})
	if err != nil {
		return
	}

	err = s.entityHub.OffTransactionService.DisableOffTransactionDetailsByOutTransNoAndOutOrderNo(ctx, q,
		&offTransaction.DisableOffTransactionDetailsByOutTransNoAndOutOrderNoParam{
			OutTransNo: outTransNo,
			OutOrderNo: outOrderNo,
		})
	if err != nil {
		return
	}

	err = s.entityHub.OffTransactionService.DisableOffTransactionOfferItemStatsByOutTransNoAndOutOrderNo(ctx, q,
		&offTransaction.DisableOffTransactionOfferItemStatsByOutTransNoAndOutOrderNoParams{
			OutTransNo: outTransNo,
			OutOrderNo: outOrderNo,
		})
	if err != nil {
		return
	}

	err = s.entityHub.OffApportionmentService.DisableOffApportionmentsByOutTransNoAndOutOrderNo(ctx, q,
		&offApportionment.DisableOffApportionmentsByOutTransNoAndOutOrderNoParam{
			OutTransNo: outTransNo,
			OutOrderNo: outOrderNo,
		})
	if err != nil {
		return
	}

	// 解锁会员优惠券
	err = s.entityHub.MemberCouponService.NormalizeMemberCouponsByOutTransNoAndOutOrderNo(ctx, q, outTransNo, outOrderNo)
	if err != nil {
		return
	}

	slog.Infof("HandleOrderCancel-外部交易(%s)-订单(%d)解锁会员优惠券 ok", outTransNo, outOrderNo)
	return
}
